#include <stdio.h>
#include <stdlib.h>

#define BUF_SIZE 1024

/*
 * A tool to copy file.
 * Compile : gcc my_copy_fread.c -o my_copy_fread
 * Usage : ./my_copy_fread file1_path file2_path
 * 
 * size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
 * size_t fwrite(const void *ptr, size_t size, size_t nmemb,
                     FILE *stream);
 */
int main(int argc, char *argv[])
{
	if (argc != 3) {
		fprintf(stderr, "Usage : %s file1_path file2_path\n", argv[0]);
		exit(1);
	}

	FILE *fp1 = NULL;
	FILE *fp2 = NULL;
	int count = 0;

	if ((fp1 = fopen(argv[1], "r")) == NULL) {
		perror("fopen()");
		exit(1);
	}
	if ((fp2 = fopen(argv[2], "w")) == NULL) {
		fclose(fp1);
                perror("fopen()");
		exit(1);
        }

	char buf[BUF_SIZE];
	int num; 
	while ((num = fread(buf, 1, BUF_SIZE, fp1)) <= 0) {
		fwrite(buf, 1, num, fp2); // important!! the number of byte to write is num not BUF_SIZE
		count++;
	}

	fclose(fp2);
	fclose(fp1);

	printf("The num of char in %s is %d\n", argv[1], count);

	exit(0);
}
